var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var encryption = require('../../../utils/encryption.js');
var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    wallet: {
      id: 0,
      type: 1,
      modifyReason: '',
      referCode: '',
      recordSn: '',
      modifyAmount: '',
      modifyIntegral: 0,
      modifyResource: '',
      modifyTime: '',
      actualPayment: '',
      payType: 1,
      payId: '',
      payTime: '',
      disabled: false,
      dis: true,
      disable: false,
      wallets_password_flag: false, //密码输入遮罩
      payPassword: '', //验证支付密码
      isFocus: false, //控制input 聚焦
      list: {},
      titleList: ["积分", "爱币"]
    }
    // password:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.globalData.hasLogin == false){
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }

    let wallet = this.data.wallet;
    wallet.modifyAmount = options.amount;
    console.log(options.disable)
    wallet.disable = options.disable;
    this.setData({
      wallet: wallet
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getListData()
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  getListData: function () {
    var that = this;
    let wallet = this.data.wallet;
    util.request(api.WalletList).then(function (res) {
      if (res.errno === 0) {
        wallet.list = res.data
        console.log(wallet.list)
        that.setData({
          wallet: wallet
        });
      }
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.payWallet
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  set_Focus() { //聚焦input
    console.log('isFocus', this.data.isFocus)
    let wallet = this.data.wallet
    wallet.isFocus = true
    this.setData({
      wallet: wallet
    })
  },
  set_notFocus() { //失去焦点
    let wallet = this.data.wallet
    wallet.isFocus = false
    this.setData({
      wallet: wallet
    })
  },

  set_wallets_password(e) { //获取钱包密码
    this.setData({
      wallets_password: e.detail.value
    });
    if (this.data.wallets_password.length == 6) { //密码长度6位时，自动验证钱包支付结果

      console.log("验证密码");
      var wallet = this.data.wallet
      wallet.payPassword = this.data.wallets_password
      this.setData({
        wallet: wallet
      });
      
      wallet_pay(this)
      this.close_wallets_password()

    }
  },

  close_wallets_password() { //关闭钱包输入密码遮罩
    var wallet = this.data.wallet
    wallet.isFocus = false
    wallet.wallets_password_flag = false
    this.setData({
      isFocus: false,
      wallets_password_flag: false,
      wallet: wallet,
      disabled: false
    })
  },
  pay() { //去支付
    pay(this)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  cancelPayWallet: function () {
    wx.navigateBack();
  },
  bindinputModifyAmount: function (event) {
    let wallet = this.data.wallet;
    wallet.modifyAmount = event.detail.value;
    this.setData({
      wallet: wallet
    });
  },
  bindinputModifyReferCode: function (event) {
    let wallet = this.data.wallet;
    wallet.referCode = event.detail.value;
    this.setData({
      wallet: wallet
    });
  },
  bindinputPassword: function (event) {
    var password = event.detail.value;
    this.setData({
      password: password
    });
  },
  payWallet: function () {
    pay(this);
    
  },
  //检查支付状态
  checkChargeStatus: function (recordSn) {
    util.request(api.WalletCheckchargestatus, {
      recordSn: recordSn
    }).then(function (res) {
      if (res.errno === 0) {
        console.log("WalletCheckchargestatus")
        console.log(res)
        wx.navigateBack();

      }
    });
  },

  //创建订单号
  createRecordSn: function () {
    var date = new Date()
    var Y = date.getFullYear()
    var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    var ss = date.getMilliseconds()
    if (ss < 10) {
      ss = '00' + ss
    } else if (ss < 100) {
      ss = '0' + ss
    }
    var result = Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString();
    // result = result.replace(/\s*/g, "");
    console.log("result = " + result)
    return result
  }
})


function pay(_this) {
  console.log('钱包支付')
  _this.setData({
    wallets_password: ''
  });
  _this.setData({
    wallets_password_flag: true,
    isFocus: true
  })


}

function wallet_pay(_this) {
  
  let that = _this;
  var wallet = that.data.wallet;
  console.log(wallet.payPassword)
  let modifyAmount = wallet.modifyAmount
  
  _this.setData({
    disabled: !_this.data.disabled,
    dis: false,
  });

  wallet.recordSn = _this.createRecordSn();

  util.request(api.WalletPayWalletMember, {
    id: wallet.id,
    userId: wallet.userId,
    type: 1,
    modifyReason: encryption.encrypt(wallet.modifyReason),
    recordSn: encryption.encrypt(wallet.recordSn),
    referCode: encryption.encrypt(wallet.referCode),
    modifyAmount: encryption.encrypt(wallet.modifyAmount),
    modifyIntegral: 0,
    modifyResource: encryption.encrypt(wallet.modifyResource),
    modifyTime: wallet.modifyTime,
    actualPayment: encryption.encrypt(wallet.actualPayment),
    payType: 3,
    payId: wallet.payId,
    payTime: wallet.payTime,
    payPassword: encryption.encrypt(wallet.payPassword)

  }, 'POST').then(function (res) {
    if (res.errno === -2) {
      wx.showModal({
        title: '提示',
        content: res.errmsg,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/ucenter/payWallet/payWallet',
            });
          } else if (res.cancel) {
            wx.navigateBack(2)
          }
        },
      });
    }
    if (res.errno === -3) {
      wx.showModal({
        title: '提示',
        content: res.errmsg,
        showCancel: false
      });
    }
    if (res.errno === -1) {
      wx.showModal({
        title: '提示',
        content: res.errmsg,
        showCancel: false
      });
    }
    if (res.errno === 0) {
      // console.log(res);
     
            if (res.data == 'success') {

              wx.showModal({
                title: '提示',
                content: "充值成功",
                success: function (res) {
                  wx.navigateBack(2);
                },
                showCancel: false
              });
              wx.setStorageSync("memberType", true)
              app.globalData.memberType = true
              // wx.navigateBack(2);
              // wx.showToast({
              //   title: '充值成功',
              //   icon: 'success',
              //   duration: 1500
              // })
            }
      
        
      
    }
  });
  /*
  1.支付成功
  2.支付失败：提示；清空密码；自动聚焦isFocus:true，拉起键盘再次输入
  */
}
  /*
  1.支付成功
  2.支付失败：提示；清空密码；自动聚焦isFocus:true，拉起键盘再次输入
  */
